﻿using System;
using System.Collections.Generic;
using System.Text;
using AspectCore.Configuration;
using AspectCore.Extensions.DependencyInjection;
using FDSimpleModelGenerator.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace FDSimpleModelGenerator.Aop
{
    /// <summary>
    /// 使用Aop服务
    /// </summary>
    public static class AopServiceExtensions
    {
        /// <summary>
        /// 使用Aop服务
        /// <remarks>使用Aop服务，前提，需要调用<see cref="UseAspectCoreServiceProviderFactory"/>方法</remarks>
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IServiceCollection AddAopService(this IServiceCollection services, Action<AopOptions> options)
        {
            var aopOptions = new AopOptions();
            options?.Invoke(aopOptions);
            services.ConfigureDynamicProxy(config =>
            {
                if (aopOptions.AopLogType == AopLogType.MethodType)
                {
                    config.Interceptors.AddTyped(typeof(SystemLogAttribute));
                }
                //config.NonAspectPredicates.add
            });
            services.AddSingleton(aopOptions);
            return services;
        }

        /// <summary>
        /// 使用Aop服务
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseAop(this IApplicationBuilder app)
        {
            //var aopOptions = app.ApplicationServices.GetService<AopOptions>();
            //var logger = app.ApplicationServices.GetService<ISystemLog<SystemLogAttribute>>();
            AopContext.Current.Initialize(app.ApplicationServices);
            return app;
        }

        /// <summary>
        /// 在Program中调用此扩展方法
        /// 以使用AspectCore服务提供者工厂
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IHostBuilder UseAspectCoreServiceProviderFactory(this IHostBuilder builder)
        {
            builder.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
            return builder;
        }
    }
}
